package ldk.apps.compass

import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.preference.Preference
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import com.android.colorpicker.ColorPickerDialog
import com.android.colorpicker.ColorPickerSwatch

/**
 * 一个简单的颜色包含颜色拾取器的Preference
 * Created by ldkxingzhe@163.com on 2018/1/30.
 */
class ColorPickerPreference(context: Context, attributeSet: AttributeSet)
    : Preference(context, attributeSet), ColorPickerSwatch.OnColorSelectedListener {

    private var colorPickerDialog: ColorPickerDialog? = null
    private val colors: IntArray
    private val colorThumbnail: View = View(context)
    private val defaultColor: Int
    private val defaultTitle: Int
    private val colorsId: Int

    init {
        val typeArray = context.obtainStyledAttributes(attributeSet, R.styleable.ColorPickerPreference)
        defaultColor = typeArray.getColor(R.styleable.ColorPickerPreference_defaultColor, Color.BLACK)
        defaultTitle = typeArray.getResourceId(R.styleable.ColorPickerPreference_title, R.string.choose_color)
        colorsId = typeArray.getResourceId(R.styleable.ColorPickerPreference_colors, R.array.colors)
        typeArray.recycle()
        colors = context.resources.getIntArray(colorsId)
    }


    override fun onBindView(view: View) {
        super.onBindView(view)
        val widgetFrame = view.findViewById(android.R.id.widget_frame) as LinearLayout
        if (colorThumbnail.parent != null){
            (colorThumbnail.parent as ViewGroup).removeView(colorThumbnail)
        }
        widgetFrame.addView(colorThumbnail, ViewGroup.LayoutParams(80, 80))
        widgetFrame.visibility = View.VISIBLE
        colorThumbnail.setBackgroundColor(getPersistedInt(defaultColor))
    }

    override fun onColorSelected(color: Int) {
        persistInt(color)
        notifyDependencyChange(false)
        notifyChanged()
    }

    override fun onClick() {
        super.onClick()
        if (colorPickerDialog == null){
            colorPickerDialog = ColorPickerDialog()
            colorPickerDialog!!.setOnColorSelectedListener(this)
        }
        colorPickerDialog!!.initialize(defaultTitle, colors, getPersistedInt(defaultColor), 5, colors.size)
        if (!colorPickerDialog!!.isVisible){
            val fragmentManager = (context as Activity).fragmentManager
            colorPickerDialog!!.show(fragmentManager, "COLOR_PICKER")
        }
    }
}